﻿using ProjBackEnd.Areas.Comprehensive.Models;
using ProjBackEnd.DBInstance;
using ProjBackEnd.Lib;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Web;

namespace ProjBackEnd.DAL
{
    /// <summary>
    /// 综合类业务逻辑
    /// </summary>
    public class comprehensiveLogic
    {
        /// <summary>
        /// 文件归档（文件名称以Userid开头）
        /// </summary>
        /// <param name="_strArcRule">归档规则名称</param>
        /// <param name="_strKey">归档关键字</param>
        /// <param name="_request">图片列表</param>
        /// <param name="_strUserid">上传文件的用户ID</param>
        /// <param name="_strComcd">上传文件的用户归属公司代码</param>
        /// <returns>返回成功归档的图片索引链表</returns>
        public static List<string> FileArchiveCommon(string _strArcRule, string _strKey, HttpRequest _request, string _strUserid,string _strComcd)
        {
            List<string> lstRet = new List<string>();
            string strRelativePath = GetFilePath(_strArcRule, _strKey);
            string strFileFullpath = GlobalSettings.FILEARCHIVEROOTPATH + strRelativePath + "\\";
            DateTime dtNow = DateTime.Now;
            Random r = new Random();
            if (!Directory.Exists(strFileFullpath)) Directory.CreateDirectory(strFileFullpath);
            HttpFileCollection files = _request.Files;
            if (files.Count == 0) return lstRet;
            ArchiveDocDataContext adctx = new ArchiveDocDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            for (int i = 0; i < files.Count; i++)
            {
                try
                {
                    HttpPostedFile file = files[i];
                    string strFileExtName = "tmp";
                    string[] strsFileExtName = file.FileName.Split('.');
                    if (strsFileExtName.Length > 1) { strFileExtName = strsFileExtName[strsFileExtName.Length - 1]; }
                    string strFileRealName = _strUserid + dtNow.ToString("yyMMddHHmmssfff") + r.Next(1000000).ToString("000000") + "." + strFileExtName;
                    while (true)
                    {
                        if (File.Exists(strFileFullpath + strFileRealName))
                            strFileRealName = _strUserid + DateTime.Now.ToString("yyMMddHHmmssfff") + r.Next(1000000).ToString("000000") + "." + strFileExtName;
                        else
                            break;
                    }
                    file.SaveAs(strFileFullpath + strFileRealName );
                    lstRet.Add(file.FileName);
                    SYS_ARCHIVETB entity = new SYS_ARCHIVETB
                    {
                        arckey = _strKey.ToUpper(),
                        arcpath = strRelativePath,
                        arcrule = _strArcRule.ToUpper(),
                        comcd = _strComcd,
                        createdt = dtNow,
                        createid = _strUserid,
                        filenm = file.FileName,
                        filerealnm = strFileRealName,
                        filestat = "",
                        extnm = strFileExtName
                    };
                    adctx.SYS_ARCHIVETB.InsertOnSubmit(entity);
                }
                catch (Exception ex) { DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message); }
            }
            adctx.SubmitChanges();
            if (adctx.Connection.State != ConnectionState.Closed) adctx.Connection.Close(); 
            return lstRet;
        }

        /// <summary>
        /// 根据归档规则名和归档关键字生成归档相对路径
        /// 格式说明：返回相对路径，格式为 xxx\xxx\xxx ，如被调用后需要衔接上级路径名或文件名，则衔接前后都要加 \
        /// </summary>
        /// <param name="_strArcRule">归档规则名</param>
        /// <param name="_strKey">归档关键字</param>
        /// <returns></returns>
        public static string GetFilePath(string _strArcRule, string _strKey)
        {
            string strRet = "Temp";
            string strDtPath = "";
            DateTime dtCreatedt;
            FinancialDataContext fcctx = new FinancialDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                switch (_strArcRule.ToUpper())
                {
                    case "CONTRACT": //合同
                        strDtPath = DateTime.Today.Year.ToString() + "\\";
                        strRet = _strArcRule + "\\" + strDtPath + _strKey;
                        break;
                    case "BIZBILL": //业务账单
                        FIN_BILLTB entityBill = fcctx.FIN_BILLTB.SingleOrDefault(n => n.billid == Convert.ToInt32(_strKey));
                        if (entityBill == default(FIN_BILLTB)) throw new Exception("未找到归档数据源");
                        dtCreatedt = entityBill.createdt;
                        strRet = _strArcRule + "\\" + dtCreatedt.Year + "\\" + dtCreatedt.Month.ToString("00") + "\\" + _strKey;
                        break;
                    case "BIZFN": //付费联系单
                        FIN_FEENOTICE entityFn = fcctx.FIN_FEENOTICE.SingleOrDefault(n => n.fnid == Convert.ToInt32(_strKey));
                        if (entityFn == default(FIN_FEENOTICE)) throw new Exception("未找到归档数据源");
                        dtCreatedt = entityFn.createdt;
                        strRet = _strArcRule + "\\" + dtCreatedt.Year + "\\" + dtCreatedt.Month.ToString("00") + "\\" + _strKey;
                        break;
                    case "OAEXPENSE": //OA报销单
                        FIN_FEENOTICE entityEx = fcctx.FIN_FEENOTICE.SingleOrDefault(n => n.fnid == Convert.ToInt32(_strKey));
                        if (entityEx == default(FIN_FEENOTICE)) throw new Exception("未找到归档数据源");
                        dtCreatedt = entityEx.createdt;
                        strRet = _strArcRule + "\\" + dtCreatedt.Year + "\\" + dtCreatedt.Month.ToString("00") + "\\" + _strKey;
                        break;
                    case "FEEDETAIL":
                        BIZ_FEE_DETAIL_fin entityFee = fcctx.BIZ_FEE_DETAIL_fin.SingleOrDefault(n => n.feeid == Convert.ToInt32(_strKey));
                        if (entityFee == default(BIZ_FEE_DETAIL_fin)) throw new Exception("未找到归档数据源");
                        dtCreatedt = entityFee.createdt;
                        strRet = _strArcRule + "\\" + dtCreatedt.Year + "\\" + dtCreatedt.Month.ToString("00") + "\\" + _strKey;
                        break;
                    case "INVOICE":
                        FIN_INVOICETB entityInvo = fcctx.FIN_INVOICETB.SingleOrDefault(n => n.invoid == Convert.ToInt32(_strKey));
                        if (entityInvo == default(FIN_INVOICETB)) throw new Exception("未找到归档数据源");
                        dtCreatedt = entityInvo.createdt;
                        strRet = _strArcRule + "\\" + dtCreatedt.Year + "\\" + dtCreatedt.Month.ToString("00") + "\\" + _strKey;
                        break;
                    default:
                        strRet = "Temp\\" + _strArcRule + "\\" + _strKey;
                        break;
                }
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message + ";" + _strArcRule + ";" + _strKey);
                strRet = "Temp\\" + _strArcRule + "\\" + _strKey;
            }
            finally { if (fcctx.Connection.State != ConnectionState.Closed) fcctx.Connection.Close(); }
            return strRet;
        }

        /// <summary>
        /// 根据归档流水号获取归档文件完整路径
        /// </summary>
        /// <param name="_iDocid">归档流水号</param>
        /// <returns></returns>
        public static string GetFileFullPathByDocid(int _iDocid)
        {
            string strReturn = "";
            ArchiveDocDataContext adctx = new ArchiveDocDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                SYS_ARCHIVETB entity = adctx.SYS_ARCHIVETB.SingleOrDefault(n => n.fileid == _iDocid);
                if (entity == default(SYS_ARCHIVETB)) throw new Exception("文件不存在;"+_iDocid.ToString());
                strReturn = entity.arcpath+"\\"+entity.filerealnm;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                strReturn = "";
            }
            finally
            {
                if (adctx.Connection.State != System.Data.ConnectionState.Closed)
                    adctx.Connection.Close();
            }
            return strReturn;
        }

        /// <summary>
        /// 根据归档规则名和归档关键字获取归档文件展示列表
        /// </summary>
        /// <param name="_strComcd">公司代码</param>
        /// <param name="_strRule">归档规则名</param>
        /// <param name="_strArcKey">归档关键字</param>
        /// <returns></returns>
        public static RespCompArcFile GetArcFileList(string _strComcd,string _strRule,string _strArcKey)
        {
            RespCompArcFile respReturn = new RespCompArcFile();
            ArchiveDocDataContext adctx = new ArchiveDocDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                List<ArcFileInfo> lst = adctx.VIEW_SYS_ARCFILEINFO.Where(n => n.arckey == _strArcKey.ToUpper() && n.arcrule == _strRule.ToUpper() && n.comcd == _strComcd && n.filestat != GlobalSettings.ENTITYOPERATION_DELETE).AsEnumerable()
                                                                                    .Select(n => new ArcFileInfo
                                                                                    {
                                                                                        creator = n.creator,
                                                                                        extnm = n.extnm,
                                                                                        fileid = n.fileid,
                                                                                        filenm = n.filenm,
                                                                                        uploaddt = n.createdt.ToString("yyyy-MM-dd HH:mm")
                                                                                    }).ToList();
                respReturn.result = new ResultArcFiles { filelist = lst };
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally { if (adctx.Connection.State != ConnectionState.Closed) adctx.Connection.Close(); }
            return respReturn;
        }

        /// <summary>
        /// 删除归档文件
        /// </summary>
        /// <param name="_strMemberid">操作用户</param>
        /// <param name="_strComcd">归属公司</param>
        /// <param name="_iFileid">文件id</param>
        /// <returns></returns>
        public static RespCompNullResultInfo DelArcFile(string _strMemberid,string _strComcd,int _iFileid)
        {
            RespCompNullResultInfo respReturn = new RespCompNullResultInfo();
            BizPurviewDataContext bpctx = new BizPurviewDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            ArchiveDocDataContext adctx = new ArchiveDocDataContext(sysLogic.GetConnString(sysLogic.DataBaseName.PROJ));
            try
            {
                int iPurCount = bpctx.PUR_MANAGERTB.Count(n => n.memberid == _strMemberid && n.comcd == _strComcd && n.purtp == GlobalSettings.PURTP_ARC);
                if (iPurCount == 0) throw new BizException("无操作权限");
                SYS_ARCHIVETB entity = adctx.SYS_ARCHIVETB.SingleOrDefault(n => n.fileid == _iFileid);
                if (entity == default(SYS_ARCHIVETB)) throw new BizException("未找到归档文件信息");
                //为保障数据安全，删除归档文件操作仅更新删除标志，并不删除文件
                //string strFileFullName = GlobalConfig.FILEARCHIVEROOTPATH + entity.arcpath + "\\" + entity.filerealnm;
                //if (File.Exists(strFileFullName)) File.Delete(strFileFullName);
                entity.filestat = GlobalSettings.ENTITYOPERATION_DELETE;
                adctx.SubmitChanges();
                SYS_SENSOPT_LOG entityLog = new SYS_SENSOPT_LOG
                {
                    newval = "",
                    oldval = entity.filerealnm,
                    optdt = DateTime.Now,
                    optid = _strMemberid,
                    optkey = entity.arcrule + ";" + entity.arckey,
                    optlb = GlobalSettings.ENTITYOPERATION_DELETE,
                    optsour = MethodBase.GetCurrentMethod().Name,
                    senslv = 0
                };
                bpctx.SYS_SENSOPT_LOG.InsertOnSubmit(entityLog);
                bpctx.SubmitChanges();
            }
            catch (BizException ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90021;
                respReturn.statusMsg = ex.Message;
            }
            catch (Exception ex)
            {
                DataUtil.WriteLog(MethodBase.GetCurrentMethod().Name, ex.Message);
                respReturn.statusCode = 90005;
                respReturn.statusMsg = "数据访问异常。" + ex.Message;
            }
            finally
            {
                if (bpctx.Connection.State != ConnectionState.Closed) bpctx.Connection.Close();
                if (adctx.Connection.State != ConnectionState.Closed) adctx.Connection.Close();
            }
            return respReturn;
        }

    }

 }